<?php
	class Product extends MY_Controller{	
		function Product() {
			parent::__construct();
			@session_start();
			$this->mod_ad->is_logged_in();
			$_SESSION['redirect'] = $this->uri->uri_string();
		}

		function index(){
			$data['vl_sort'] = "DESC";	
			$data['title'] = "Sản phẩm";
			$data['table'] = 'product';
			$data['controller'] = 'product';
			$data['content_admin'] = 'back_end/product/index';
			$data['sort'] = 'ASC';
			
			//lay ra noi xuat xu
			$data['origin'] = $this->db->get('origin')->result_array(); 
			//chọn thương hiệu 
			$data['brand'] = $this->db->get('brand')->result_array();
			//chọn nhà sản xuất
			$data['suppliers'] = $this->db->get('suppliers')->result_array();
			//lay ra danh muc san pham
			$data['category_product'] = $this->mod_lib->findOrderList('category_product');
			
			//lay ra cac danh muc cap 1
			$data['category_admin_1'] = $this->db->get_where('admin_menu',array('level' => 1))->result_array();
			//lay ra cac danh muc cap 2
			$data['category_admin_2'] = $this->db->get('admin_menu',array('level' => 2))->result_array();
			//lay ra category hien tai	
			$uri_value = $this->uri->segment(2);
			$this->db->select('root_path,id');
			$data['category_admin_active'] = $this->db->get_where('admin_menu',array('controller' => $uri_value))->row_array();
			
			//liet ke ra cac san pham 
			$join = array (
				'category_product' => 'product.category_product_id = category_product.id'
			);
			 
			//lay ra anh san pham
			$this->db->where('status',1);
			$data['image_prd']= $this->db->get('product_images')->result_array();
			
			$per_page = 10;
			$uri = 4;
			$data['query_prd']      =  $this->mod_lib->join('product','product.*,category_product.name AS category_product_name',array(),$join,$per_page,$this->uri->segment($uri),array("id"=>"desc"));																													
			$config['base_url']     =  site_url('back_end/product/index/');
			$config['total_rows']   =  $this->db->count_all('product');
			$config['per_page']     =  $per_page; 
			$config['uri_segment']  =  $uri; 
			$this->pagination->initialize($config);
			
			$this->load->view('back_end/template_backend',$data);
		} 
		
		function sort($field,$sort = ''){
			$per_page = 10;
			$uri = 4;
			$data['title'] = "Sắp xếp - sản phẩm";
			$data['table'] = 'product';
			$data['controller'] = 'product';
			$data['list_categoryProduct'] = $this->db->get('category_product')->result_array();
			$data['content_admin'] = 'back_end/product/index';
			$this->db->order_by('parent_id','asc');
			$data['category_admin'] = $this->db->get('admin_menu')->result_array();
			
			$uri_value_4 =  $this->uri->segment(4);
			$uri_value_5 =  $this->uri->segment(5);
			
			$_SESSION['order_sort_product'] = array(
				$uri_value_4 => $uri_value_5 
			);
			
			$_SESSION['sort'] = $sort;
			$_SESSION['field'] = $field;
			
			if ($sort == 'DESC') {
				$data['sort'] =  'ASC';
			} else if($sort == 'ASC') {
				$data['sort'] =  'DESC';
			}

			//lay ra cac danh muc cap 1
			$data['category_admin_1'] = $this->db->get_where('admin_menu',array('level' => 1))->result_array();
			//lay ra cac danh muc cap 2
			$data['category_admin_2'] = $this->db->get('admin_menu',array('level' => 2))->result_array();
			//lay ra category hien tai	
			$uri_value = $this->uri->segment(2);
			$this->db->select('root_path,id');
			$data['category_admin_active'] = $this->db->get_where('admin_menu',array('controller' => $uri_value))->row_array();
			
			//liet ke ra cac san pham 
			$join = array (
				'category_product' => 'product.category_product_id = category_product.id'
			);
			
			//lay ra anh san pham
			$this->db->where('status',1);
			$data['image_prd']= $this->db->get('product_images')->result_array();
			
			$per_page = 6;
			$uri = 4;
			$data['query_prd']      =  $this->mod_lib->join('product','product.*,category_product.name AS category_product_name',array(),$join,$per_page,$this->uri->segment($uri),$_SESSION['order_sort_product']);																													
			$config['base_url']     =  site_url('back_end/product/index/');
			$config['total_rows']   =  $this->db->count_all('product');
			$config['per_page']     =  $per_page; 
			$config['uri_segment']  =  $uri; 
			$this->pagination->initialize($config);
			
			$this->load->view('back_end/template_backend',$data);
		}
		
		function search(){
			$data['vl_sort'] = "DESC";	
			$data['sort'] = 'ASC';
			$data['table'] = 'product';
			$check_search = $this->input->POST('formSearch');
			$per_page = 10;
			$data['title'] = "Tìm kiếm - Sản phẩm";
			$data['controller'] = 'product';
			$data['list_categoryProduct'] = $this->db->get('category_product')->result_array();
			$this->db->order_by('parent_id','asc');
			$data['category_admin'] = $this->db->get('admin_menu')->result_array();
			$data['content_admin'] = 'back_end/product/index';

			if ($this->input->POST('category_product_id')) {
				$where = array(
					'category_product_id' => $this->input->POST('category_product_id')
				);	
			} else {
				$where = array();
			}
			
			if(!empty($check_search)){
				$_SESSION['like'] = array('product.name' =>$this->input->POST('nameSearch'));																												
			} else {
				$_SESSION['like'] = array('product.name' => '');
			}
			
			if(empty($_SESSION['order_sort_product'])){
				$_SESSION['order_sort_product'] = array();	
			}
			
			//lay ra cac danh muc cap 1
			$data['category_admin_1'] = $this->db->get_where('admin_menu',array('level' => 1))->result_array();
			//lay ra cac danh muc cap 2
			$data['category_admin_2'] = $this->db->get('admin_menu',array('level' => 2))->result_array();
			//lay ra category hien tai	
			$uri_value = $this->uri->segment(2);
			$this->db->select('root_path,id');
			$data['category_admin_active'] = $this->db->get_where('admin_menu',array('controller' => $uri_value))->row_array();
			
			//lay ra noi xuat xu
			$data['origin'] = $this->db->get('origin')->result_array(); 
			//chọn thương hiệu 
			$data['brand'] = $this->db->get('brand')->result_array();
			//chọn nhà sản xuất
			$data['suppliers'] = $this->db->get('suppliers')->result_array();
			//lay ra danh muc san pham
			$data['category_product'] = $this->mod_lib->findOrderList('category_product');
			
			//join 
			$join['category_product'] =  'product.category_product_id = category_product.id';	

			if ($this->input->POST('brand_id')){
				$join['brand']            =  'product.brand_id = brand.id';	
			}
			if ($this->input->POST('origin_id')){
				$join['origin']           =  'product.origin_id = origin.id';
			}
			if ($this->input->POST('suppliers_id')){
				$join['suppliers']        =  'product.suppliers_id = suppliers.id';
			}
			
			//lay ra anh san pham
			$this->db->where('status',1);
			$data['image_prd']= $this->db->get('product_images')->result_array();
			
			$data_search            =  $this->mod_lib->join_like('product','product.*,category_product.name AS category_product_name',$_SESSION['like'],$where,$join,$per_page,'',$_SESSION['order_sort_product']);																
			$data['query_prd']      =  $this->mod_lib->join_like('product','product.*,category_product.name AS category_product_name',$_SESSION['like'],$where,$join,$per_page,'',$_SESSION['order_sort_product']);																													
			$config['base_url']     =  site_url('back_end/product/search/');
			$config['total_rows']   =  count($data_search);
			$config['per_page']     =  $per_page;
			$config['uri_segment']  =  4; 
			$this->pagination->initialize($config);		
			
			$this->load->view('back_end/template_backend',$data);	
		}
		
		function add($id = null, $id_prd = null){			
			$data['title']			= "Thêm sản phẩm";
			$data['content_admin'] = 'back_end/product/add';
			$data['list_menu'] = $this->mod_lib->findOrderListCategory('category_product');
			$_SESSION['image_name'] = ' ';
			$data['category_admin'] = $this->db->get('admin_menu')->result_array();
			
			//lay ra cac danh muc cap 1
			$data['category_admin_1'] = $this->db->get_where('admin_menu',array('level' => 1))->result_array();
			//lay ra cac danh muc cap 2
			$data['category_admin_2'] = $this->db->get('admin_menu',array('level' => 2))->result_array();
			//lay ra category hien tai	
			$uri_value = $this->uri->segment(2);
			$this->db->select('root_path,id');
			$data['category_admin_active'] = $this->db->get_where('admin_menu',array('controller' => $uri_value))->row_array();
			
			//lay ra noi xuat xu
			$data['origin'] = $this->db->get('origin')->result_array(); 
			//chọn thương hiệu 
			$data['brand'] = $this->db->get('brand')->result_array();
			//chọn nhà sản xuất
			$data['suppliers'] = $this->db->get('suppliers')->result_array();
			//lay ra don vi tinh
			$data['unit'] = $this->db->get('unit')->result_array();
			//lay ra danh muc san pham
			$data['category_product'] = $this->mod_lib->findOrderList('category_product');
			
			if ($id_prd > 0) {
				$_SESSION['add_common'] = $id_prd; 
				
				$this->db->select('image');
				$this->db->where('id',$id_prd);
				$prd_img_1 = $this->db->get('product')->row_array();
			
				$this->db->where('status',0);	
				$this->db->where('product_id',$id_prd);
				$prd_img_2 = $this->db->get('product_images')->result_array();
				
				$this->db->where('product_id',$id_prd);
				$prd_video = $this->db->get('product_video')->row_array();
				
				$data['active_tab'] = $id_prd;
				$data['add_common'] = $this->db->get_where('product',array('id' => $id_prd))->row_array();
				
				$data['add_image_1'] = $prd_img_1;
				$data['add_image_2'] = $prd_img_2;
		
				if (count($prd_video) > 0) {
					$data['add_video'] = $this->db->get_where('product_video',array('product_id' => $id_prd))->row_array();
				} 	
			} else {
				if ($id == 0) {
					unset($_SESSION['add_common']);
					unset($_SESSION['atv_tab']);
					$_SESSION['value_id'] = 0;
						
					redirect('back_end/product/add/1');	
				}
				if (empty($_SESSION['add_common'])) { 
					if ($id == 2 || $id == 3 || $id == 3 || $id == 4 || $id == 5) {
						if(empty($_SESSION['add_description'])){
							$_SESSION['value_id'] = $id;
							redirect('back_end/product/add/1');		
						}
					}
				}	
				if (!empty($_SESSION['atv_tab'])) {
					$data['active_tab'] = $_SESSION['atv_tab'];  
				}
			
				if (!empty($_SESSION['add_common'])) {
					// lay ra gia tri chung cua san pham
					$data['add_common'] = $this->db->get_where('product',array('id' => $_SESSION['add_common']))->row_array();
				}
				
				if (!empty($_SESSION['add_image'])) {
					$this->db->where('status',1);
					$data['add_image_1'] = $this->db->get_where('product_images',array('product_id' => $_SESSION['add_image']))->row_array();
			
					$this->db->where('status',0);
					$data['add_image_2'] = $this->db->get_where('product_images',array('product_id' => $_SESSION['add_image']))->result_array();
				}
				
				if (!empty($_SESSION['add_video'])) {
					$data['add_video'] = $this->db->get_where('product_video',array('product_id' => $_SESSION['add_video']))->row_array();
				}
			}	
			$this->load->view('back_end/template_backend',$data);
		}
		
		function edit_common($id) {
			$edit = $this->input->post('editForm_common');
			
			if(!empty($edit)){
				$where = array(
		  			'id' => $id
		  		);
		  		$order = array(
		  			'id' => 'DESC'
		  		);			
				$data_value = array (
					'name'                      =>trim($this->input->post('name')),
					'category_product_id'       =>trim($this->input->post('category_product_id')),
					'code'                      =>trim($this->input->post('code')),	
					'alias'						=>convertAlias($this->input->post('name')),
					'origin_id'                 =>trim($this->input->post('origin_id')),
					'brand_id'                  =>trim($this->input->post('brand_id')),
					'suppliers_id'              =>trim($this->input->post('suppliers_id')),
					'unit_id'					=>trim($this->input->post('unit_id')),
					'cost'						=>trim($this->input->post('cost')),
					'wholesale_cost'			=>trim($this->input->post('wholesale_cost')),
					'purchase_cost'			    =>trim($this->input->post('purchase_cost')),
					'quantity'					=>trim($this->input->post('quantity')),
					'edit_date'					=>date ("Y-m-d H:m:s"),
					'status'     				=>trim($this->input->post('status'))	
				);
				
				if($this->mod_lib->update('product',$where,$order,$data_value)){	
					$this->session->set_flashdata('msview', 'Sửa thông tin chung sản phẩm thành công !');
					$this->mod_lib->insert_log('Edit product',$_SESSION['admin_id']);
				} else {
					$this->session->set_flashdata('msview', 'Thêm sản phẩm thất bại !');
				} 	
				redirect('back_end/product/add/2/'.$_SESSION['add_common']);
			}else {
				redirect('back_end/product/add/1/'.$_SESSION['add_common']);
			}	
		}
		
		function add_common() {
			$add = $this->input->post('addForm_common');
			
			if(!empty($add)){					
				$data_value = array (
					'name'                      =>trim($this->input->post('name')),
					'category_product_id'       =>trim($this->input->post('category_product_id')),
					'code'                      =>trim($this->input->post('code')),	
					'alias'						=>convertAlias($this->input->post('name')),
					'origin_id'                 =>trim($this->input->post('origin_id')),
					'brand_id'                  =>trim($this->input->post('brand_id')),
					'suppliers_id'              =>trim($this->input->post('suppliers_id')),
					'unit_id'					=>trim($this->input->post('unit_id')),
					'cost'						=>trim($this->input->post('cost')),
					'wholesale_cost'			=>trim($this->input->post('wholesale_cost')),
					'purchase_cost'			    =>trim($this->input->post('purchase_cost')),
					'quantity'					=>trim($this->input->post('quantity')),
					'create_date'				=>date ("Y-m-d H:m:s"),
					'status'     				=>trim($this->input->post('status'))	
				);
				
				if($this->mod_lib->insert('product',$data_value)){
					$id = $this->db->insert_id();		
					$this->session->set_flashdata('msview', 'Thêm thông tin chung sản phẩm thành công !');
					$this->mod_lib->insert_log('Add product',$_SESSION['admin_id']);
				} else {
					$this->session->set_flashdata('msview', 'Thêm thông tin chung sản phẩm thất bại !');
				} 	
				
				$_SESSION['atv_tab'] = $id; 
				$_SESSION['add_common'] = $id;   
				
				redirect('back_end/product/add/2/'.$_SESSION['add_common']);	
			}else {
				
				redirect('back_end/product/add/1/'.$_SESSION['add_common']);
			}	
		}
		
		function add_description($id) {
			$add = $this->input->post('addForm_description');
			
			if(!empty($add)){
				$where = array(
		  			'id' => $id
		  		);
		  		$order = array(
		  			'id' => 'DESC'
		  		);					
				$data_value = array (
					'description'                      =>trim($this->input->post('description')),
					'specifications'                   =>trim($this->input->post('specifications')),
					'manual' 			               =>trim($this->input->post('manual')),
					'tags'                   		   =>trim($this->input->post('tags')),
					'edit_date'						   =>date ("Y-m-d H:m:s")		
				);
				
				if($this->mod_lib->update('product',$where,$order,$data_value)){
					$this->session->set_flashdata('msview', 'Thêm mô tả sản phẩm thành công !');
					$this->mod_lib->insert_log('Add product',$_SESSION['admin_id']);
				} else {
					$this->session->set_flashdata('msview', 'Thêm mô tả sản phẩm thất bại !');
				} 	
				
				$_SESSION['add_description'] = $id;   
				
				redirect('back_end/product/add/3/'.$_SESSION['add_common']);	
			}else {
				redirect('back_end/product/add/2/'.$_SESSION['add_common']);	
			}	
		}
		
		function add_image($id) {
			$add = $this->input->post('addForm_image');
			
			if(!empty($add)){
				if ($_FILES['image']['name'] !== '') {
					upload($_FILES['image'], 'images/img_product/');
					
					$where = array(
	  					'id' => $id
	  				);
			  		
		  			$order = array(
		  				'id' => 'DESC' 
		  			);
		  			
					$data_img = array (
						'name'		 =>  $_SESSION['image_name'],		
		            );
		                     
				   	$this->mod_lib->update('product',$where,$order,$data_img);    
				}
								
				if ($_FILES['image_1']['name'] !== '') {
					upload($_FILES['image_1'], 'images/img_product/');
					$image1 = array (
								'product_id'	    => $id,
								'image'			    => $_SESSION['image_name'],
								'status'			=> 0		
				             );
				    $this->mod_lib->insert('product_images',$image1);    
				}
					
				if ($_FILES['image_2']['name'] !== '') {
					upload($_FILES['image_2'], 'images/img_product/');
					$image2 = array (
								'product_id'	    => $id,
								'image'			    => $_SESSION['image_name'],
								'status'			=> 0		
				             );
				    $this->mod_lib->insert('product_images',$image2);          
				}
				
				if ($_FILES['image_3']['name'] !== '') {
					upload($_FILES['image_3'], 'images/img_product/');
					$image3 = array (
								'product_id'	    => $id,
								'image'			    => $_SESSION['image_name'],
								'status'			=> 0		
				             );
				    $this->mod_lib->insert('product_images',$image3);        
				}
				
				if ($_FILES['image_4']['name'] !== '') {
					upload($_FILES['image_4'], 'images/img_product/');
					$image4 = array (
								'product_id'	    => $id,
								'image'			    => $_SESSION['image_name'],
								'status'			=> 0			
				             );
				    $this->mod_lib->insert('product_images',$image4);            
				}
				
				$this->session->set_flashdata('msview', 'Thêm ảnh sản phẩm thành công !');
				
				$this->mod_lib->insert_log('Add product image',$_SESSION['admin_id']);
		
				$_SESSION['add_image'] = $id;   
				
				redirect('back_end/product/add/4/'.$_SESSION['add_common']);	
			}else {
				redirect('back_end/product/add/3/'.$_SESSION['add_common']);	
			}
		}
		
		function add_video($id) {
			$add = $this->input->post('addForm_video');
			
			if(!empty($add)){ 
				$video = array (
					'product_id'	    => $id,
					'name'			    => trim($this->input->post('name')),
					'link'			    => trim($this->input->post('link')),
					'description'		=> trim($this->input->post('description')),
					'status'			=> $this->input->post('status')		
	            );
				
	            $_SESSION['add_video'] = $id;  
	            
				if ($this->mod_lib->insert('product_video',$video)) {
					$this->session->set_flashdata('msview', 'Thêm video thành công !');
				} else {
					$this->session->set_flashdata('msview', 'Thêm video thất bại !');
				}
				    
				redirect('back_end/product/add/5/'.$_SESSION['add_common']);	
			} else {
				redirect('back_end/product/add/4/'.$_SESSION['add_common']);		
			}
		}
		
		function edit_video($id){
			$add = $this->input->post('addForm_video');
			
			if(!empty($add)){ 
				$where = array(
	  				'product_id' => $id
	  			);
			  		
	  			$order = array(
	  				'product_id' => 'DESC' 
	  			);
				$video = array (
					'name'			    => trim($this->input->post('name')),
					'link'			    => trim($this->input->post('link')),
					'description'		=> trim($this->input->post('description')),
					'status'			=> $this->input->post('status')		
	            );

				if($this->mod_lib->update('product_video',$where,$order,$video)) {
					$this->session->set_flashdata('msview', 'Sửa video thành công !');
				} else {
					$this->session->set_flashdata('msview', 'Sửa video thất bại !');
				}
				 
				redirect('back_end/product/add/5/'.$_SESSION['add_common']);	
			} else {
				
				redirect('back_end/product/add/4/'.$_SESSION['add_common']);
			}
		}
		
		function edit_image($id) {
			$add = $this->input->post('addForm_image');
			
			$data['product_images'] = $this->db->get_where('product_images',array( 'product_id' => $id))->result_array();

			if(!empty($add)){
				foreach ($data['product_images'] as $prd) {
					if($_FILES['image_'.$prd['id']]['size'] > 0) {
						upload($_FILES['image_'.$prd['id']], 'images/img_product/');
						$where = array(
			  				'id' => $prd['id']
			  			);
			  		
			  			$order = array(
			  				'id' => 'DESC' 
			  			);
			  			
						$image_up = array (
							'image'			    => $_SESSION['image_name']		
			            );     
			             
					    $this->mod_lib->update('product_images',$where,$order,$image_up );
					}
				}
				
				$ct = count($data['product_images']);		
				if ($ct < 4) {
					for ($i = $ct; $i < 4 ; $i++) {
						$pl = $i + 1;
						if ($_FILES['image_'.$pl]['name'] !== '') {
							upload($_FILES['image_'.$pl], 'images/img_product/');
							$image_pl = array (
										'product_id'	    => $id,
										'image'			    => $_SESSION['image_name']		
						             );
						    $this->mod_lib->insert('product_images',$image_pl);    
						}	
					}	
				}
				
				if ($_FILES['image']['name'] !== '') {
					upload($_FILES['image'], 'images/img_product/');
				    $where_dd = array(
		  				'id' => $id
		  			);
			  		
		  			$order_dd = array(
		  				'id' => 'DESC' 
		  			);
		  			
					$image_dd = array (
						'image'			    => $_SESSION['image_name']		
		             );   
		             
				    $this->mod_lib->update('product',$where_dd,$order_dd,$image_dd );         
				}
				
				$this->session->set_flashdata('msview', 'Sửa ảnh sản phẩm thành công !');
								
				$this->mod_lib->insert_log('Add product image',$_SESSION['admin_id']);
		
				$_SESSION['add_image'] = $id;   
				
				redirect('back_end/product/add/4/'.$_SESSION['add_common']);
			}else {
				
				redirect('back_end/product/add/3/'.$_SESSION['add_common']);
			}
		}
		
		function delete_all() {
			$ids =  $this->input->post('value_id');
			
			foreach ($ids as $ids_arr) {
				//xoa video san pham
				$this->db->where('product_id', $ids_arr);
				$this->db->delete('product_video');
				
				//xoa anh san pham
				$this->db->where('product_id', $ids_arr);
				$this->db->delete('product_images');
				
				$this->mod_lib->deleteRecord('product', $ids_arr);
			}
				
			redirect('back_end/product');
		}

		function delete($id) {
			if(!empty($id)){
			//xoa video san pham
			$this->db->where('product_id', $id);
			$this->db->delete('product_video');
			
			//xoa anh san pham
			$this->db->where('product_id', $id);
			$this->db->delete('product_images');
			
			if($this->mod_lib->deleteRecord('product',$id)){
					$this->session->set_flashdata('msview', 'Xóa thành công !');
				} 
			} else {
				$this->session->set_flashdata('msview', 'Xóa thất bại !');
			}		
			
			redirect('back_end/product');
		}
}
?>